import {useEffect, useReducer, useState} from "react";
import {action, observable} from 'mobx'
import {observer} from 'mobx-react'
// 处理泛型
type Person<T> = {
  [p in keyof T]?:T[p]
}

// 定义state的类型
interface ObjTypes {
  [key:string]:any
}

const useMulState2= <T extends ObjTypes >(props:T):[T,(props:Person<T>)=>void]=>{
  let arr:any[] = [];
  for(let key in props){
    let [state,setState] = useState(props[key]);
    arr.push({
      key:key,
      state:state,
      call:setState,
    })
  }

  const setState = (props:Person<T>)=>{
    for(let key in props){
      arr.forEach(item=>{
        if(item.key == key){
          item.call(props[key]);
        }
      })
    }
  }

  let state:ObjTypes = {};
  arr.forEach(item=>{
    state[item.key] = item.state;
  })

  return [
    state as T,
    setState
  ]
}

export const useMulState = <T extends ObjTypes >(props:T):[T,(props:Person<T>)=>void]=>{
  const [data,dispatch] = useReducer((data:T,action:Person<T>)=>{
    let newData = {...data};
    for(let keya in action){
      for(let keyd in newData){
        if(keya == keyd){
          newData[keyd] = action[keya] as T[Extract<keyof T, string>];
        }
      }
    }
    return newData;
  },props)

  const setState = (props:Person<T>)=>{
    dispatch(props);
  }
  return [
    data,
    setState
  ]

}


const useMulState3 = <T extends ObjTypes >(props:T):[T,(props:Person<T>)=>void]=>{
  const state = observable({
    ...props
  })

  const setState = action((props:Person<T>)=>{
    for(let key in props){
      state[key] = props[key] as T[Extract<keyof T, string>];
    }
  })

  return [
    state,
    setState
  ]

}